package com.example.sxt_practise.IO;

import java.io.*;
import java.util.Objects;

/**
 * 文件拷贝,流和流对接
 * @author gaofeng
 * @date 2022年05月08日 16:36
 */
public class FileCopyTest {
    public static void main(String[] args) {
        // 1. 创建源
//        File sourceDir = new File("dir/test2/song.txt");
//        File destDir = new File("dir/test2/song2.txt");
        File sourceDir = new File("receive.jpeg");
        File destDir = new File("receive_copy.jpeg");
        copyFile(sourceDir, destDir);
    }

    private static void copyFile(File source, File dest) {
        // 2.选择流
        InputStream inputStream = null ;
        OutputStream outputStream = null ;
        try {
            inputStream = new FileInputStream(source) ;
            outputStream = new FileOutputStream(dest, true) ;
            // 3.操作
            byte[] flush = new byte[1024 * 2] ;
            int len = -1 ;
            while ((len = inputStream.read(flush)) != -1) {
                outputStream.write(flush, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(inputStream)) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (Objects.nonNull(outputStream)) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
